package org.suwenqian.audiovideosummary.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

public class VideoUtils {
    /**
     * 使用FFMpeg获取视频时长(秒)
     */
    public static long getVideoDuration(MultipartFile file) throws Exception {
        // 1. 将MultipartFile保存为临时文件
        File tempFile = File.createTempFile("video", ".mp4");
        file.transferTo(tempFile);

        // 2. 构建FFMpeg命令
        String[] cmd = {
                "ffmpeg",
                "-i",
                tempFile.getAbsolutePath(),
                "-f",
                "null",
                "-"
        };

        // 3. 执行命令并解析输出
        Process process = Runtime.getRuntime().exec(cmd);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getErrorStream()));

        String line;
        long duration = 0;

        while ((line = reader.readLine()) != null) {
            if (line.contains("Duration:")) {
                String time = line.substring(line.indexOf("Duration:") + 10, line.indexOf(","));
                duration = convertTimeToSeconds(time);
                break;
            }
        }

        // 4. 清理临时文件
        tempFile.delete();

        return duration;
    }

    /**
     * 将HH:MM:SS格式时间转换为秒
     */
    private static long convertTimeToSeconds(String time) {
        String[] parts = time.split(":");
        long hours = Long.parseLong(parts[0]);
        long minutes = Long.parseLong(parts[1]);
        double seconds = Double.parseDouble(parts[2]);
        return hours * 3600 + minutes * 60 + (long) seconds;
    }
}